package xyz.xiangyushui.dao;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import xyz.xiangyushui.javaBean.sales.SalesDailyRecord;

public class SalesHistoryDao extends Dao{
	private final String year="2016";
	
	public void updateSalesMonthlyCommodity(int year,int month,String commodityIdName,int storeId){
		int s=db.executeUpdate("update salesMonthlyCommodity set sales=sales+1 where year=? and month=? and commodityIdName=? and storeId=?",new Object[]{year,month,commodityIdName,storeId});
		if(s>0){
			return ;
		}else{
			db.executeUpdate("insert into salesMonthlyCommodity(year,month,storeId,commodityIdName,sales) values(?,?,?,?,?)", new Object[]{year,month,storeId,commodityIdName,1});
		}
	}
	
	
	
	public void updateSalesDailyRecord(String date,int storeId,double value){
		int s = db.executeUpdate("update salesDailyRecord set total=total+"+value+" where date=? and storeId=?",new Object[]{date,storeId} );
		if(s>0){
			return;
		}else{
			db.executeUpdate("insert into salesDailyRecord(date,storeId,total) values(?,?,?)",new Object[]{date,storeId,value} );
		}
	}
	
	public List<SalesDailyRecord> getDailyTotal(int storeId,int month){
		List<SalesDailyRecord> list=new LinkedList<>();
		String start;
		String end;
		if(month>=1&&month<=8){
			start=year+"-"+"0"+month+"-"+"01";
			end=year+"-"+"0"+(month+1)+"-"+"01";
		}else if(month==9){
			start=year+"-"+"0"+month+"-"+"01";
			end=year+"-"+(month+1)+"-"+"01";
		}else if(month>9&&month<12){
			start=year+"-"+month+"-"+"01";
			end=year+"-"+(month+1)+"-"+"01";
		}else{
			start=year+"-"+month+"-"+"01";
			end=year+"-"+month+"-"+"31";
		}
		
		System.out.println("start:"+start);
		System.out.println("end:"+end);
		List<Object> l =db.excuteQuery("select date,total from salesDailyRecord where date>=? and date<? ", new Object[]{start,end});
		for (Object o : l) {
			@SuppressWarnings("unchecked")
			Map<String, Object> m = (Map<String, Object>) o;
			SalesDailyRecord s=new SalesDailyRecord();
			s.setDate(((java.sql.Date) m.get("date")).toString());
			s.setTotal((double) m.get("total"));
			list.add(s);
		}
		System.out.println(list.size());
		return list;
	}
	
	public Map<String,Integer> getTopSalesCommodity(int storeId,int month){
		Map<String,Integer> map=new HashMap<>();
		List<Object> l =db.excuteQuery("select commodityIdName,sales from salesMonthlyCommodity where month=? and storeId=? order by sales DESC limit 0,3", new Object[]{month,storeId});
		for (Object o : l) {
			@SuppressWarnings("unchecked")
			Map<String, Object> m = (Map<String, Object>) o;
			map.put((String) m.get("commodityIdName"), (Integer) m.get("sales"));
		}
		return map;
	}
	
	
}
